package com.wx.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.wx.entity.SysMenu;
import com.wx.entity.SysMenuExample;
import com.wx.entity.SysRoleMenuExample;
import com.wx.entity.SysUserMenuExample;
import com.wx.service.SysMenuService;
import com.wx.service.SysRoleMenuService;
import com.wx.service.SysUserMenuService;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.common.util.GsonUtil;
import com.zyht.common.util.Page;

/**
 * <b>描述：</b>	系统菜单管理<br/>
 * <b>作者：</b>zrb <br/>
 * <b>修改日期：</b>2016年1月8日 - 上午11:06:04<br/>
 */
@Controller
@RequestMapping("admin/menu")
public class SysMenuController extends AbsManageBaseController{

	@Resource
	private SysMenuService sysMenuService;
	
	@Resource
	private SysUserMenuService sysUserMenuService;
	
	@Resource
	private SysRoleMenuService sysRoleMenuService;
	
	private final String MENU_SHOW_FALSE = "0";
	
	private final String MENU_SHOW_TRUE = "1";
	
	/**
	 * <b>作者:</b> zrb<br/>
	 * <b>修改时间：</b>2016年1月8日 - 下午2:41:16<br/>
	 * <b>功能说明：</b>菜单列表页	<br/>
	 * @param currentPage
	 * @param menuName
	 * @param model
	 * @return
	 */
	@RequestMapping("index")
	public String index(Integer currentPage, @RequestParam(required=false,defaultValue="0",value="parentId") Integer parentId, String menuName, Model model){
		if(parentId==null || parentId<0){
			parentId=0;
		}
		model.addAttribute("parentId", parentId);
		if(null==currentPage){
			currentPage = 1;
		}
		SysMenuExample example = new SysMenuExample();
		com.wx.entity.SysMenuExample.Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(menuName)){
			criteria.andMenuNameLike("%"+menuName+"%");
		}
		criteria.andParentIdEqualTo(parentId); 
		example.setOrderByClause(" menu_order desc");
		
		String pSize = PropertiesUtils.getConfig("paganation_page_size");
		int pageSize = Integer.valueOf(pSize);
		PageHelper.startPage(currentPage, pageSize);
		com.github.pagehelper.Page<SysMenu> pageInfo = (com.github.pagehelper.Page<SysMenu>) this.sysMenuService.list(example);
		Page<SysMenu> page = new Page<SysMenu>((int)pageInfo.getTotal(), currentPage, pageSize);
		page.setRecordList(pageInfo);
		model.addAttribute("page", page);
		model.addAttribute("menuName", menuName);
		
		List<SysMenu> list = new ArrayList<SysMenu>();
		Set<Integer> muids = new HashSet<Integer>();
		muPath(list,muids,parentId,0);
		Collections.reverse(list);
		model.addAttribute("muPath", list);
		
		return "sys/menu/index";
	}
	
	private void muPath(List<SysMenu> list,Set<Integer> muids, Integer parentId,int i) {
		i++;
		if(i>10){
			return;
		}
		if(list==null || parentId==null || parentId==0 ||muids==null){
			return;
		}
		SysMenu mu = sysMenuService.findOneById(parentId);
		if(mu==null){
			return;
		}
		if(muids.contains(parentId)){
			return;
		}
		muids.add(parentId);
		list.add(mu);
		if(mu.getId()!=null && mu.getParentId()!=null ){
			muPath(list,muids,mu.getParentId(),i);
		}
	}

	/**
	 * <b>作者:</b> zrb<br/>
	 * <b>修改时间：</b>2016年1月8日 - 下午2:40:56<br/>
	 * <b>功能说明：</b>跳转菜单修改页面<br/>
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("toedit")
	public String edit(Integer id, Model model){
		List<Integer> ids = new ArrayList<Integer>();
		
		if(null!=id){
			SysMenu menu = this.sysMenuService.findOneById(id);
			model.addAttribute("bean", menu);
			ids.add(menu.getParentId());
		}else{
			model.addAttribute("bean", new SysMenu());
		}
		getMenus(model,ids);
		return "sys/menu/add_update";
	}
	
	
	
	/**
	 * <b>作者:</b> zrb<br/>
	 * <b>修改时间：</b>2016年1月8日 - 下午3:04:36<br/>
	 * <b>功能说明：</b>跳转新增页面<br/>
	 * @param model
	 * @return 
	 */
	@RequestMapping("toadd")
	public String add(@RequestParam(required=false,defaultValue="0",value="parentId") Integer parentId,Model model){
		//取出所有的父菜单类型
		SysMenu k = new SysMenu();
		if(parentId!=null){
			k.setParentId(parentId);
		}
		model.addAttribute("bean", k);
		Integer[] ids = {parentId};
		getMenus(model,new ArrayList<Integer>(Arrays.asList(ids)));
		
		return "sys/menu/add_update";
	}

	/**
	 * 获取所有非隐藏菜单
	 * @param model
	 */
	private void getMenus(Model model, List<Integer> ids) {
		SysMenuExample example = new SysMenuExample();
		example.createCriteria().andMenuShowNotEqualTo("0");
		List<SysMenu> list = this.sysMenuService.list(example);
		if(ids!=null &&!ids.isEmpty()){
			Map<Integer,SysMenu > map = new HashMap<Integer,SysMenu >();
			for(SysMenu menu : list){
				if(menu!=null && menu.getId() !=null && !map.containsKey(menu.getId())){
					map.put(menu.getId(), menu);
				}
			}
			Set<Integer> set = new HashSet<Integer>();
			for (Integer id : ids) {
				menuPath(set, map, id);
			}
			for(SysMenu menu : list){
				if(set.contains(menu.getId()) ){
					menu.setOpen(true);
				}
			}
		}
		
		SysMenu sysMenuP= new SysMenu();
		sysMenuP.setId(0);
		sysMenuP.setParentId(null);
		sysMenuP.setMenuName("顶级菜单");
		sysMenuP.setOpen(true);
		list.add(sysMenuP);
		
		Gson gson = GsonUtil.getGsonWithAnnotation();
		String nodeList = gson.toJson(list);
		model.addAttribute("nodes", nodeList);
	}

	private void menuPath(Set<Integer> set, Map<Integer, SysMenu> map, Integer menuId) {
		Set<Integer> settmp = new HashSet<Integer>();
		menuPath(set, map, settmp, menuId);
		settmp.clear();
		settmp=null;
	}
	private void menuPath(Set<Integer> set, Map<Integer, SysMenu> map,Set<Integer> settmp , Integer menuId) {
		if(menuId==null || set==null || map==null || settmp==null){
			return;
		}
		SysMenu menu = map.get(menuId);
		if(menu!=null && !settmp.contains(menuId)){
			set.add(menuId);
			settmp.add(menuId);
			if(menu.getParentId()!=null){
				menuPath(set, map, settmp, menu.getParentId());
			}
		}else{
			return;
		}
	}

	/**
	 * <b>作者:</b> zrb<br/>
	 * <b>修改时间：</b>2016年1月8日 - 下午3:09:40<br/>
	 * <b>功能说明：</b>保存菜单信息<br/>
	 * @param bean
	 * @return
	 */
	@RequestMapping("persist")
	public String saveOrUpdate(SysMenu bean, Model model){
		if(bean==null){
			return message("参数错误", "/sys/menu/msg", model);
		}
		if(bean.getParentId()==null || bean.getParentId()==0){
			bean.setParentId(0);
		}else{
			SysMenu parentMenu = this.sysMenuService.findOneById(bean.getParentId());
			if(parentMenu==null || "0".equals(parentMenu.getMenuShow())){
				return message("父级菜单错误", "/sys/menu/msg", model);
			}
		}
		if(null!=bean.getId()){
			this.sysMenuService.updateById(bean);
		}else{
			this.sysMenuService.addOne(bean);
		}
		return "redirect:/admin/menu/msg";
	}
	
	@RequestMapping("del")
	public String delete(Integer id, Model model){
		if(null!=id){
			this.sysMenuService.deleteById(id);
			SysRoleMenuExample roleEx = new SysRoleMenuExample();
			roleEx.createCriteria().andMenuIdEqualTo(id);
			this.sysRoleMenuService.deleteByExample(roleEx);
			SysUserMenuExample userEx = new SysUserMenuExample();
			userEx.createCriteria().andMenuIdEqualTo(id);
			this.sysUserMenuService.deleteByExample(userEx);
		}
		return "redirect:/admin/menu/msg";
	}
	
	/**
	 * <b>作者:</b> zrb<br/>
	 * <b>修改时间：</b>2016年1月8日 - 下午2:57:33<br/>
	 * <b>功能说明：</b>停用菜单<br/>
	 * @param id
	 * @param response
	 */
	@RequestMapping("stopit")
	public void stopMenu(Integer id, String status, HttpServletResponse response){
		if(null!=id){
			SysMenu menu = this.sysMenuService.findOneById(id);
			if(null!=menu){
				if(status.equals(MENU_SHOW_FALSE)){
					menu.setMenuShow(MENU_SHOW_FALSE);
				}else if(status.equals(MENU_SHOW_TRUE)){
					menu.setMenuShow(MENU_SHOW_TRUE);
				}
				this.sysMenuService.updateById(menu);
			}
		}
		JSONObject obj = new JSONObject();
		obj.put("status",200);
		writeJson(response,obj.toJSONString());
	}
	
	@RequestMapping("msg")
	public String msg(Model model){
		model.addAttribute("redirect","admin/menu/index");
		return "message";
	}
	
	private String message(String msg,String redirect, Model model){
		model.addAttribute("msg",msg);
		model.addAttribute("redirect",redirect);
		return "message";
	}
}
